package com.aube.interact.taste.card;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.interact.taste.R;
import com.aube.interact.taste.controller.DataManager;
import com.aube.interact.taste.model.OptionResultModel;
import com.aube.interact.taste.model.ReportResultModel;
import com.aube.interact.taste.model.TimeLinePiece;
import com.aube.interact.taste.model.VoteData;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hill on 16/12/23.
 */

public class QuizViewEx extends BaseCardNew implements View.OnClickListener {
    private final String TAG = "Aube/QuizViewEx";

    private VoteData mVoteData;

    private ImageView mWinImage;

    private List<QuizOptionViewEx> mOptionList = new ArrayList<>();

    private int mWinImgMargin, mWinImgTopMargin;

    private int mCorrectIndex = -1;
    private int mPreselectedIndex = -1;

    public QuizViewEx(Context context) {
        this(context, null);
    }
    public QuizViewEx(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public QuizViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    @Override
    public void init(final TimeLinePiece data, ChannelDetail detail) {
        super.init(data, detail);
        initView();
    }

    @Override
    protected void initView() {
        Utils.Log(TAG, "initView");
        LayoutInflater.from(getContext()).inflate(R.layout.aube_intera_layout_sdk_quizex, this);

        // basic view
        mRoot = (FrameLayout) findViewById(R.id.sdk_quizex_root);
        mOptionGp = (LinearLayout) findViewById(R.id.sdk_quizex_optiongp);
        mFoldText = (TextView) findViewById(R.id.sdk_quizex_expand);
        mCloseView = findViewById(R.id.sdk_quizex_close);
        mDivisionView = findViewById(R.id.sdk_quizex_division_line);
        mTitleText = (TextView) findViewById(R.id.sdk_quizex_titletext);
        mParticipantsText = (TextView) findViewById(R.id.sdk_quizex_people);
        mBetterCloseView = findViewById(R.id.sdk_quizex_closeclickview);
        mWinImage = (ImageView) findViewById(R.id.sdk_quizex_win);

        mTitleText.setText(mData.title);

        super.initView();

        fillOption();

        Utils.Log(Utils.LogType.DEBUG, TAG, "init end");
    }

    private void fillOption() {
        mPreselectedIndex = DataManager.getInstance(mContext).getIndex(mData.getRid());
        mOptionLineHeight = Utils.dip2px(mContext, 0.5f);
        mDivisionViewHeight = Utils.dip2px(mContext, 5);
        mWinImgTopMargin = Utils.dip2px(mContext, 25);

        if(mData == null || mData.optionSize() == 0) return;

        if(StringUtils.isNotBlank(mData.getQuizYPicUrl()) && !mData.getQuizYPicUrl().equalsIgnoreCase("http://static02.aube-tv.com/"))
            ImageLoader.getInstance(getContext()).fillImage(mWinImage, mData.getQuizYPicUrl(), Utils.dip2px(mContext, 49), Utils.dip2px(mContext, 49));

        for(int i = 0; i < mData.optionSize(); i++) {
            QuizOptionViewEx quizOption = new QuizOptionViewEx(mContext);
            quizOption.initView(mData.getOptions().get(i));
            quizOption.setTag("QuizOptionViewEx_" + i);
            quizOption.setOnClickListener(this);
            quizOption.setLayoutParams(i);
            mOptionList.add(quizOption);
            ((LinearLayout)mOptionGp.getChildAt(0)).addView(quizOption);
        }

        mVoteData = new VoteData(mContext);
        mVoteData.compose(mData);

        updateView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if(mOptionGp.getVisibility() == View.VISIBLE) {
            if(!mBAnimating) {
                mOptionGpHeight = mOptionGp.getMeasuredHeight();
            }
            mRootHeight = mTitleText.getMeasuredHeight() + mOptionGpHeight + mParticipantsText.getMeasuredHeight() + mTasteStyleHeight;
        } else {
            mRootHeight = mTitleText.getMeasuredHeight() + mDivisionViewHeight + mParticipantsText.getMeasuredHeight() + mTasteStyleHeight;
        }

        if(mBAnimating) {
            mRootHeight = mAnimHeight;
        }

        mOptionGp.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mOptionGpWidth = mOptionGp.getMeasuredWidth();
        mRootWidth = mOptionGpWidth + BasicMargin * 2 + mTasteStyleWidth;

        measureChild(getChildAt(0), View.MeasureSpec.makeMeasureSpec(mRootWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(mRootHeight, View.MeasureSpec.EXACTLY));
        setMeasuredDimension(View.MeasureSpec.makeMeasureSpec(mRootWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(mRootHeight, View.MeasureSpec.EXACTLY));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        mDivisionViewTop = mTitleText.getMeasuredHeight();
        mDivisionView.layout(BasicMargin, mDivisionViewTop, mRootWidth - BasicMargin, mDivisionViewTop + mDivisionViewHeight);

        mOptionGpTop =  mTitleText.getMeasuredHeight();
        mOptionGp.layout(BasicMargin, mOptionGpTop, mRootWidth - BasicMargin, mOptionGpTop + mOptionGp.getMeasuredHeight());
    }

    @Override
    public void onClick(View v) {
        if(mData.showQuizResult)
            return;

        for(int i = 0; i < mOptionList.size(); i++) {
            QuizOptionViewEx optionViewEx = mOptionList.get(i);
            if(v.getTag().equals(optionViewEx.getTag())) {
                report(mVoteData.mRid, mVoteData.getReportOptionId(i), mVoteData.getReportCancelId(i), true);
                mVoteData.update(i);
                Utils.Log(TAG, "[onClick] equal. v.getTag() = " + v.getTag());
            }
        }

        updateView();
    }

    private void updateView() {
        for(int i = 0; i < mOptionList.size(); i++) {
            QuizOptionViewEx optionViewEx = mOptionList.get(i);
            optionViewEx.mOptionImg.setBackgroundResource(mVoteData.IsFocusedIndex(i) ? R.drawable.bg_optionimg_orangeselected : R.drawable.bg_optionimg_unselected);
            optionViewEx.mPercentText.setText(mVoteData.IsFocused() ? Html.fromHtml(doPercentHtmlFormat(mVoteData.getOptionPercent(mData.getOptionIdByIndex(i)))) : "");
            optionViewEx.mPercentText.setTextSize(mVoteData.IsFocusedIndex(i) ? 13 : 12);
            optionViewEx.mOptionText.setTextSize(mVoteData.IsFocusedIndex(i) ? 13 : 12);

            if(mCorrectIndex == i) {
                mWinImage.setVisibility(VISIBLE);
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mWinImage.getLayoutParams();
                params.topMargin = mWinImgTopMargin + mDivisionViewTop;
                params.leftMargin = BasicMargin + i * (getResources().getDimensionPixelSize(R.dimen.optionimg_width) + Utils.dip2px(mContext, 10)) + Utils.dip2px(mContext, 5);
            }
        }

        mParticipantsText.setText(String.valueOf(mVoteData.getTotalCount()) + " 人参加");
    }

    /**
     * 重写卡片展开动画,跟默认卡片动画有区别
     */
    @Override
    protected void startExpandAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim");

        if(mData.showQuizResult) {
            mWinImage.setVisibility(VISIBLE);
        }

        mBAnimating = true;

        mOptionGp.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        mOptionGpHeight = mOptionGp.getMeasuredHeight();
        final float oriHeight = mRoot.getHeight();
        final float targetHeight = mTitleText.getMeasuredHeight() + mParticipantsText.getMeasuredHeight() + mOptionGpHeight + mTasteStyleHeight;

        final ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = mAnimHeight = (int) (oriHeight + (targetHeight - oriHeight) * animValue);

                mRoot.setLayoutParams(params);
                mFoldText.setAlpha(animValue);
                mOptionGp.setAlpha(animValue);
                mWinImage.setAlpha(animValue);
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBAnimating = false;
                mBExpanded = true;

                // load preset data if not fold default
                if(!mBPreloadDataLoaded)
                    loadPresetData();
            }
        });

        anim.setDuration(400);
        anim.setTarget(mRoot);
        anim.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startExpandAnim done");
    }

    /**
     * 重写卡片收起动画,跟默认卡片动画有区别
     */
    @Override
    protected void startCollapseAnim() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim");

        mBAnimating = true;

        final float oriHeight = mRoot.getHeight();
        final float targHeight = mTitleText.getMeasuredHeight() + mParticipantsText.getMeasuredHeight() + mDivisionViewHeight + mTasteStyleHeight;

        final ValueAnimator anim = ValueAnimator.ofFloat(0.0f, 1.0f);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animValue = (float) animation.getAnimatedValue();

                LayoutParams params = (LayoutParams) mRoot.getLayoutParams();
                params.height = mAnimHeight = (int) (oriHeight - (oriHeight - targHeight) * animValue);

                mRoot.setLayoutParams(params);
                mFoldText.setAlpha(animValue);
                mRoot.requestLayout();

                mOptionGp.setAlpha(1 - animValue);
                mWinImage.setAlpha(1 - animValue);
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBAnimating = false;
                mBExpanded = false;
                mOptionGp.setVisibility(View.GONE);
                mWinImage.setVisibility(GONE);
                mDivisionView.setVisibility(View.VISIBLE);
            }
        });

        anim.setDuration(400);
        anim.setTarget(mRoot);
        anim.start();

        Utils.Log(Utils.LogType.DEBUG, TAG, "startCollapseAnim done");
    }

    @Override
    public String getType() {
        return TYPE_GUESS;
    }

    @Override
    public void doNext() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "doNext");
        if(iSender != null)
            iSender.startSync(mData.getRid(), true);
    }

    @Override
    public void syncData(OptionResultModel response) {
        Utils.Log(TAG, "syncData");
        updateView();
    }

    @Override
    public boolean IsPreviewDataSynced() {
        return true;
    }

    @Override
    public void syncPreviewData(ReportResultModel result) {
    }

    /**
     * 在卡片出现动画结束后被调用
     */
    @Override
    protected void loadPresetData() {
        if(mData.showQuizResult) {
            Utils.Log(TAG, "loadPresetData: showQuizResult");
            mCorrectIndex = mData.getRightAnswerIndex();
        }

        Utils.Log(TAG, "loadPresetData: mPreselectedIndex = " + DataManager.getInstance(mContext).getIndex(mData.getRid()));
        if(!mVoteData.getPresetDataLoad() && mPreselectedIndex >= 0) {
            Utils.Log(TAG, "[loadPresetData] mPreselectedIndex = " + mPreselectedIndex);
            mVoteData.restorePreselectedIndex(mPreselectedIndex);
            updateView();
            mVoteData.setPresetDataLoad(true);
        }
    }
}